package com.snj.visangedu.calendar;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;

import java.util.LinkedList;

public class Pager extends HorizontalScrollView // implements OnTouchListener, OnGestureListener
{

  private static final String TAG = "StudyPlan";

  private LinearLayout contents;
  private LinkedList<OnPageChangeListener> listeners;

  private static final int SWIPE_MIN_DISTANCE = 10;
  private static final int SWIPE_THRESHOLD_VELOCITY = 200;
  
  public boolean isFirst = true;

  public Pager(Context ctx, AttributeSet attrs) {
    super(ctx, attrs);
    contents = new LinearLayout(ctx);
    contents.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT));

    addView(contents);
    setVerticalScrollBarEnabled(false);
    setHorizontalScrollBarEnabled(false);
  }

  @Override
  public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    // int specMode = MeasureSpec.getMode(widthMeasureSpec);
    int specSize = MeasureSpec.getSize(widthMeasureSpec);

    for (int i = 0; i < contents.getChildCount(); i++) {
      View child = contents.getChildAt(i);
      if (child.getLayoutParams().width != specSize) {
        child.setLayoutParams(new LinearLayout.LayoutParams(specSize, LayoutParams.FILL_PARENT));
      }

    }
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
  }


  @Override
  protected float getLeftFadingEdgeStrength() {
    return 0.0f;
  }

  @Override
  protected float getRightFadingEdgeStrength() {
    return 0.0f;
  }

  public void addPage(View child) {
    int width = getWidth();
    child.setLayoutParams(new LayoutParams(width, LayoutParams.FILL_PARENT));
    contents.addView(child);
    contents.requestLayout();

    firePageCountChanged();
  }

  private int iCount;
  private GestureDetector mGestureDetector;
  private int mActiveFeature = 0;

  public void setFeatureItems(int count) {

    iCount = count;

    SetPageFast(1);

    setOnTouchListener(new View.OnTouchListener() {
      // @Override
      public boolean onTouch(View v, MotionEvent event) {
        // If the user swipes
        if (mGestureDetector.onTouchEvent(event)) {

          // Log.d(TAG, "mGestureDetector, = " + event.getAction());

          if (event.getAction() == MotionEvent.ACTION_UP) {
            if (mMyScrollViewListener != null) {
              Log.d(TAG, "mGestureDetector, page = " + GetPage());
              mMyScrollViewListener.onScrollChanged(GetPage(), 0, 0, 0);
            }
          }
          return true;

        } else if (event.getAction() == MotionEvent.ACTION_UP
            || event.getAction() == MotionEvent.ACTION_CANCEL) {

          int scrollX = v.getScrollX();
          int featureWidth = v.getMeasuredWidth();

          int stepWidth = featureWidth / 2;

          mActiveFeature = ((scrollX + stepWidth) / featureWidth);
          int scrollTo = mActiveFeature * featureWidth;

          smoothScrollTo(scrollTo, 0);

          if (mMyScrollViewListener != null) {
            mMyScrollViewListener.onScrollChanged((scrollTo + (featureWidth / 2)) / featureWidth,
                0, 0, 0);
          }

          return true;
        } else {
          return false;
        }
      }
    });
    mGestureDetector = new GestureDetector(new MyGestureDetector());

  }

  class MyGestureDetector extends SimpleOnGestureListener {
    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
      if (e1 == null || e2 == null) return false;

      try {
        // right to left
        if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
            && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {

          int featureWidth = getMeasuredWidth();
          mActiveFeature = (mActiveFeature < (iCount - 1)) ? mActiveFeature + 1 : iCount - 1;
          smoothScrollTo(mActiveFeature * featureWidth, 0);
          return true;
        }
        // left to right
        else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
            && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
          int featureWidth = getMeasuredWidth();
          mActiveFeature = (mActiveFeature > 0) ? mActiveFeature - 1 : 0;

          smoothScrollTo(mActiveFeature * featureWidth, 0);
          return true;
        }
      } catch (Exception e) {
        Log.e(TAG, "error Fling event:" + e.getMessage());
      }
      return false;
    }
  }

  public void SetPage(int page) {
    if (page < iCount) {
      smoothScrollTo(page * getWidth(), 0);
      Log.d(TAG, "SetPage ScrollTo : " + page * getWidth() + ", " + page * getHeight());
    }
  }

  public void SetPageFast(int page) {
	  
	  
	  scrollTo(page * getWidth(), 0);
	  
      Log.d(TAG, "SetPageFast ScrollTo : " + page * getWidth() + ", " + page * getHeight());
      
  }

  public void SetPageFastNonUpdate(int page) {
    scrollTo(page * getWidth(), 0);
  }

  public int GetPage() {
    int width = getMeasuredWidth();
    return (getScrollX() + (width / 2)) / width;
  }

  public interface MyScrollViewListener {
    public abstract void onScrollChanged(int l, int t, int oldl, int oldt);
  }

  MyScrollViewListener mMyScrollViewListener;

  public void setMyScrollViewListener(MyScrollViewListener listener) {
    mMyScrollViewListener = listener;
  }

  @Override
  protected void onScrollChanged(int l, int t, int oldl, int oldt) {

    super.onScrollChanged(l, t, oldl, oldt);

    if (listeners != null) {
      for (OnPageChangeListener list : listeners) {
        list.onPageChange(this);
      }
    }
  }

  public boolean hasPage(View v) {
    return contents.indexOfChild(v) != -1;
  }

  public void removePage(View v) {
    contents.removeView(v);
    firePageCountChanged();

  }

  public int getCurrentPage() {
    int width = getWidth();
    return (getScrollX() + width / 2) / width;
  }

  public int getPageCount() {
    return contents.getChildCount();
  }

  public void removeAllPages() {
    contents.removeAllViews();
    firePageCountChanged();

  }

  private void firePageCountChanged() {
    if (listeners != null) {
      for (OnPageChangeListener list : listeners) {
        list.onPageCountChange(this);
      }
    }
  }



  public void addOnPageChangeListener(OnPageChangeListener onPageChangeListener) {
    if (listeners == null) {
      listeners = new LinkedList<OnPageChangeListener>();
    }
    listeners.add(onPageChangeListener);
  }

  public boolean removeOnPageChangeListener(OnPageChangeListener l) {
    if (listeners != null) {
      return listeners.remove(l);
    } else
      return false;
  }

}
